package ru.ifmo.croak.impl.stress.query.team1;

import ru.ifmo.croak.api.QueryRequest;

import java.util.Random;

/**
 * @author Roman Kolganov
 * 26.05.11
 */
public class QueryRequestGenerator {

    private static final int SET_AUTHOR_INVPROB = 4;
    private static final int SET_TEXT_INVPROB = 4;
    private static final int SET_LIMIT_INVPROB = 4;
    private static final int MIN_LIMIT = 10;
    private static final int MAX_LIMIT = 1000;
    private static final int CAPACITY = (int) 1e5;

    private final RandomAccessConcurrentSet<String> authors =
            new RandomAccessConcurrentSet<String>(CAPACITY);
    private final RandomAccessConcurrentSet<String> words =
            new RandomAccessConcurrentSet<String>(CAPACITY);

    public void addAuthor(String author, Random rand) {
        authors.add(author, rand);
    }

    public void addAuthor(String author) {
        addAuthor(author, null);
    }

    public void addWord(String word, Random rand) {
        words.add(word, rand);
    }

    public void addWord(String word) {
        addWord(word, null);
    }

    public QueryRequest nextQueryRequest(boolean setAuthor, boolean setText,
                                         boolean setLimit, Random rand) {
        QueryRequest request = new QueryRequest();
        if (setAuthor) {
            request.setAuthor(authors.randomElement(rand));
        }
        if (setText) {
            request.setText(words.randomElement(rand));
        }
        if (setLimit) {
            request.setLimit(SafeRandom.nextInt(rand, MIN_LIMIT, MAX_LIMIT));
        }
        return request;
    }

    public QueryRequest nextQueryRequest(boolean setAuthor, boolean setText,
                                         boolean setLimit) {
        return nextQueryRequest(setAuthor, setText, setLimit, null);
    }

    public QueryRequest nextQueryRequest(Random rand) {
        return nextQueryRequest(SafeRandom.nextBoolean(rand, SET_AUTHOR_INVPROB),
                SafeRandom.nextBoolean(rand, SET_TEXT_INVPROB),
                SafeRandom.nextBoolean(rand, SET_LIMIT_INVPROB), rand);
    }

    public QueryRequest nextQueryRequest() {
        return nextQueryRequest(null);
    }
}
